﻿using System.Collections.Specialized;
using System.Configuration;

namespace Network.Server
{
    public class ServerConfigurator
    {
        #region PROPERTIES

        /// <summary>
        /// IPv4 address string
        /// </summary>
        public string IPAddress { get; set; }

        /// <summary>
        /// Port
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// Client timeout in s.
        /// </summary>
        public int ClientTimeout { get; set; }

        /// <summary>
        /// Client handler update time in ms.
        /// </summary>
        public int HandlerUpdateTime { get; set; }

        /// <summary>
        /// Client update time in ms.
        /// </summary>
        public int ClientUpdateTime { get; set; }

        #endregion

        #region CONSTRUCTOR

        private ServerConfigurator()
        {
            IPAddress = "127.0.0.1";
            Port = 9999;
            ClientTimeout = 30;
            HandlerUpdateTime = 100;
            ClientUpdateTime = 5;
        }

        #endregion

        #region SINGLETONE CONSTRUCTION

        private static ServerConfigurator _instance;

        public static ServerConfigurator Instance
        {
            get { return (_instance = _instance ?? new ServerConfigurator()); }
        }

        #endregion

        #region METHODS
        
        public void LoadFromAppConfig()
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string[] values;
            values = appSettings.GetValues("IPAddress");
            if (values != null)
                IPAddress = values[0];

            int temp;
            values = appSettings.GetValues("Port");
            if (values != null && int.TryParse(values[0], out temp))
                Port = temp;

            values = appSettings.GetValues("ClientTimeout");
            if (values != null && int.TryParse(values[0], out temp))
                ClientTimeout = temp;

            values = appSettings.GetValues("HandlerUpdateTime");
            if (values != null && int.TryParse(values[0], out temp))
                HandlerUpdateTime = temp;

            values = appSettings.GetValues("ClientUpdateTime");
            if (values != null && int.TryParse(values[0], out temp))
                ClientUpdateTime = temp;
        }

        #endregion

    }
}
